package com.panfeng.xcloud.boss.provider.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.panfeng.xcloud.boss.provider.member.config.GeetestConfig;
import com.panfeng.xcloud.boss.provider.member.dto.request.EmailCodeReqDTO;
import com.panfeng.xcloud.boss.provider.member.dto.request.SMSCodeReqDTO;
import com.panfeng.xcloud.boss.provider.member.dto.request.SecondaryVerifyReqDTO;
import com.panfeng.xcloud.boss.provider.member.dto.request.StartCaptchaReqDTO;
import com.panfeng.xcloud.boss.provider.member.dto.response.SecondaryVerifyRespDTO;
import com.panfeng.xcloud.boss.provider.member.dto.response.StartCaptchaRespDTO;
import com.panfeng.xcloud.boss.provider.member.enums.LoginAccountTypeEnum;
import com.panfeng.xcloud.boss.provider.member.model.GeetestLib;
import com.panfeng.xcloud.boss.provider.member.service.IGeetestService;
import com.panfeng.xcloud.boss.provider.member.service.IUserSMSService;
import com.panfeng.xcloud.common.core.constants.BlConstants;
import com.panfeng.xcloud.common.core.constants.RedisConstants;
import com.panfeng.xcloud.common.core.enums.ResponseStatusEnum;
import com.panfeng.xcloud.common.core.enums.VerifiyCodeTypeEnum;
import com.panfeng.xcloud.common.core.exceptions.BaseBizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class GeetestServiceImpl implements IGeetestService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IUserSMSService iUserSMSService;

    @Autowired
    private GeetestConfig geetestConfig;

    @Override
    public StartCaptchaRespDTO initialize(StartCaptchaReqDTO reqBean) {
        GeetestLib gtSdk = new GeetestLib(geetestConfig.getGeetest_id(), geetestConfig.getGeetest_key(), geetestConfig.getNewfailback());

        HashMap<String, String> param = new HashMap<>(16);
        param.put("user_id", reqBean.getUserId());
        param.put("client_type", reqBean.getClientType());
        /*param.put("ip_address", reqBean.getIpAddress());*/

        int gtServerStatus = gtSdk.preProcess(param);
        JSONObject gtSdkJsonObj = JSON.parseObject(gtSdk.getResponseStr());
        redisTemplate.opsForValue().set(RedisConstants.GT_STATUS + reqBean.getUserId(), String.valueOf(gtServerStatus), BlConstants.GT_EXPIRE_TIME, TimeUnit.HOURS);

        StartCaptchaRespDTO startCaptchaRespDTO = new StartCaptchaRespDTO();
        startCaptchaRespDTO.setSuccess(gtServerStatus);
        startCaptchaRespDTO.setChallenge(gtSdkJsonObj.getString("challenge"));
        startCaptchaRespDTO.setGt(gtSdkJsonObj.getString("gt"));

        return startCaptchaRespDTO;
    }

    @Override
    public SecondaryVerifyRespDTO secondaryVerify(SecondaryVerifyReqDTO reqBean) {
        SecondaryVerifyRespDTO respBean = new SecondaryVerifyRespDTO();
        GeetestLib gtSdk = new GeetestLib(geetestConfig.getGeetest_id(), geetestConfig.getGeetest_key(), geetestConfig.getNewfailback());
        String generateAccountIdFront = redisTemplate.opsForValue().get(RedisConstants.GT_STATUS + reqBean.getUserId());

        HashMap<String, String> param = new HashMap<>();
        param.put("user_id", reqBean.getUserId());
        param.put("client_type", reqBean.getClientType());
        /*param.put("ip_address", reqBean.getIpAddress());*/

        int gtResult;
        if (Integer.valueOf(generateAccountIdFront) == 1) {
            //gt-server正常，向gt-server进行二次验证
            try {
                gtResult = gtSdk.enhencedValidateRequest(reqBean.getChallenge(), reqBean.getValidate(), reqBean.getSeccode(), param);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                log.info(">>> 极验进行二次验证异常：{}",e);
                throw new BaseBizException(ResponseStatusEnum.GT_ERROR);
            }
        } else {
            // gt-server非正常情况下，进行failback模式验证
            log.info(">>>>> failback:use your own server captcha validate <<<<<");
            gtResult = gtSdk.failbackValidateRequest(reqBean.getChallenge(), reqBean.getValidate(), reqBean.getSeccode());
        }
        if (gtResult == 1) {
            // 验证成功，调用发送验证码接口
            respBean.setStatus("success");
            respBean.setVersion(gtSdk.getVersionInfo());

            if(reqBean.getAccountType() == LoginAccountTypeEnum.MOBILE.getCode()){
                VerifiyCodeTypeEnum verifiyCodeTypeEnum = VerifiyCodeTypeEnum.of(reqBean.getBusinessType().byteValue());
                SMSCodeReqDTO sMSCodeReqDTO = new SMSCodeReqDTO();
                sMSCodeReqDTO.setVerifiyCodeTypeEnum(verifiyCodeTypeEnum);
                sMSCodeReqDTO.setLoginMobileNo(reqBean.getAccountNumber());
                sMSCodeReqDTO.setUserName(reqBean.getAccountNumber());
                iUserSMSService.sendSMSAndGetCode(sMSCodeReqDTO);
            }else if(reqBean.getAccountType() == LoginAccountTypeEnum.EMAIL.getCode()){
                VerifiyCodeTypeEnum verifiyCodeTypeEnum = VerifiyCodeTypeEnum.of(reqBean.getBusinessType().byteValue());
                EmailCodeReqDTO emailCodeReqDTO = new EmailCodeReqDTO();
                emailCodeReqDTO.setEmail(reqBean.getAccountNumber());
                emailCodeReqDTO.setVerifiyCodeTypeEnum(verifiyCodeTypeEnum);
                iUserSMSService.sendEmailAndGetCode(emailCodeReqDTO);
            }
        }else {
            // 验证失败
            log.info(">>>>> secondaryVerify 验证失败：{} <<<<<", reqBean.getUserId());
            respBean.setStatus("fail");
            respBean.setVersion(gtSdk.getVersionInfo());
        }
        return respBean;
    }
}
